import React, { useState } from 'react';
import { Select, Icon, Modal } from '@whalecloud/fdx';
import UserSelect from '@components/UserSelect';
import '../batchEdit.module.less';

const DesignUserSelect = (props: any) => {
  const { defaultValue, value, onChange } = props;
  const [modalVisible, setModalVisible] = useState(false);
  const [userValue, setUserValue] = useState(value || defaultValue);
  const [modalValue, setModalValue] = useState('');

  /**
   * 点击弹出弹框
   */
  const handleClick = () => {
    setModalVisible(true);
    setModalValue(userValue);
  }

  /**
   * 点击弹框确定按钮
   */
  const handleOk = () => {
    setModalVisible(false);
    setUserValue(modalValue);
    if (onChange) {
      onChange(modalValue[0]?.userId)
    }
  }

  /**
   * select change
   * @param curValue // change value
   */
  const handleChange = (curValue: any) => {
    setUserValue([]);
    if (onChange) {
      onChange(curValue[0]?.userId || null)
    }
  }

  return (
    <div className="design-user-select" >
      <Select
        mode="tags"
        placeholder="Please select"
        value={userValue?.map((curValue: any) => curValue.userName) || []}
        open={false}
        showArrow
        suffixIcon={<Icon onClick={handleClick} type="plus" />}
        onChange={handleChange}
      />
      <Modal
        title={<span className="mt-1 mb-2">添加成员</span>}
        width={520}
        visible={modalVisible}
        onCancel={() => setModalVisible(false)}
        onOk={handleOk}
        okText="确定"
        cancelText="取消"
        className="design-user-select-modal"
      >
        <UserSelect
          value={(modalValue && modalValue[0]?.userId) || ''}
          onChange={(curValue: any) => setModalValue(curValue)}
        />
      </Modal>
    </div>
  );
};

export default DesignUserSelect;
